<template>
	<view class="content">
		<!-- 自定义导航栏 -->
		<view class="nav-bar">
			<view class="status-bar" :style="{height: statusBarHeight + 'px'}"></view>
			<view class="nav-content">
				<view class="nav-left" @click="goBack">
					<u-icon name="arrow-left" color="#333" size="18"></u-icon>
				</view>
				<view class="nav-title">积分商城</view>
				<view class="nav-right">
					<view class="nav-icon" @click="shareProduct">
						<u-icon name="share" color="#333" size="18"></u-icon>
			</view>
			</view>
			</view>
		</view>
		
		<!-- 积分展示区 -->
		<view class="points-display" :style="{marginTop: (statusBarHeight + 44) + 'px'}">
			<view class="points-label">可用积分:</view>
			<view class="points-value">{{userIntegral}}分</view>
		</view>
		
		<!-- 选项卡 -->
		<view class="tabs">
			<view class="tab-item" :class="{ active: currentTab === 'free' }" @click="switchTab('free')">
				免费
			</view>
			<view class="tab-item" :class="{ active: currentTab === 'bring' }" @click="switchTab('bring')">
				带来注册
			</view>
			<view class="tab-item" :class="{ active: currentTab === 'explain' }" @click="switchTab('explain')">
				明细
			</view>
		</view>
		
		<!-- 商品列表 -->
		<scroll-view 
			class="product-list" 
			v-if="currentTab === 'free'"
			scroll-y
			:refresher-enabled="true"
			:refresher-triggered="refreshing"
			@refresherrefresh="onRefresh"
		>
			<!-- 加载状态 -->
			<view v-if="loading" class="loading-container">
				<view class="loading-spinner"></view>
				<text class="loading-text">加载中...</text>
			</view>
			
			<!-- 商品网格 -->
			<view v-else-if="products.length > 0" class="product-grid">
				<view class="product-item" v-for="(item, index) in products" :key="item.id" @click="goToDetail(item)">
					<image class="product-image" :src="item.image" mode="aspectFill" :lazy-load="true"></image>
					<view class="product-info">
						<view class="product-name">{{item.name}}</view>
						<view class="product-stats">
							<text class="stock">库存: {{item.stock}}</text>
							<text class="sales">销量: {{item.salesVolume}}</text>
						</view>
						<view class="product-points">{{item.points}}积分</view>
						<view class="product-price">￥{{item.price}}</view>
					</view>
				</view>
			</view>
			
			<!-- 空状态 -->
			<view v-else class="empty-state">
				<image src="http://121.36.197.175:19000/test/empty-product.png" mode="aspectFit" class="empty-image"></image>
				<text class="empty-text">暂无积分商品</text>
		</view>
		</scroll-view>
		
		<view class="empty-content" v-else>
			<text>该功能正在开发中...</text>
		</view>
	</view>
</template>

<script>
	import uIcon from "uview-ui/components/u-icon/u-icon.vue"
	import request from '@/util/request.js'
	
	export default {
		components: {
			uIcon
		},
		data() {
			return {
				statusBarHeight: 0,
				userInfo: {
					userId: '',
					userAcc: '',
					userName: ''
				},
				userIntegral: 0,
				token: '',
				currentTab: 'free',
				products: [],
				loading: false,
				refreshing: false
			}
		},
		onLoad() {
			// 获取状态栏高度
			const systemInfo = uni.getSystemInfoSync();
			this.statusBarHeight = systemInfo.statusBarHeight;
			
			this.getUserInfo();
			this.token = uni.getStorageSync('token') || '';
			this.initPageData();
		},
		onShow() {
			this.token = uni.getStorageSync('token') || '';
			this.getUserInfo();
			this.initPageData();
		},
		methods: {
			goBack() {
				uni.navigateBack();
			},
			switchTab(tab) {
				this.currentTab = tab;
			},
			// 跳转到商品详情页
			goToDetail(item) {
				// 传递完整的商品数据，避免重复请求
				const productData = encodeURIComponent(JSON.stringify(item));
				uni.navigateTo({
					url: `/pages/shop/IntegralDetail?id=${item.id}&productData=${productData}`
				});
			},
			// 获取用户信息
			getUserInfo() {
				try {
					const userInfo = uni.getStorageSync('userInfo');
					if (userInfo) {
						this.userInfo.userId = userInfo.userId;
						this.userInfo.userAcc = userInfo.userAcc;
						this.userInfo.userName = userInfo.userName;
					} else {
						// 未登录处理
						uni.navigateTo({
							url: '/pages/login/login'
						});
					}
				} catch (e) {
					console.error('获取用户信息失败', e);
				}
			},
			// 初始化页面数据
			async initPageData() {
				if (!this.userInfo.userId) {
					return;
				}
				
				// 并行获取用户积分和商品列表
				await Promise.all([
					this.getUserIntegral(),
					this.getProductList()
				]);
			},
			
			// 获取积分
			async getUserIntegral() {
				try {
					const res = await request({
						url: '/user-service/user/integral',
						method: 'GET',
						data: {
							userId: this.userInfo.userId
						}
					});
				
					// 获取积分
					const integral = res.data.integral || 0;
					this.userIntegral = integral;
				} catch (error) {
					console.error('获取积分失败', error);
					if (error.code === 401) {
						// token失效，跳转登录页
						uni.navigateTo({
							url: '/pages/login/login'
						});
					} else {
						uni.showToast({
							title: '获取积分失败',
							icon: 'none'
						});
					}
				}
			},
			
			// 获取积分商品列表
			async getProductList() {
				try {
					this.loading = true;
					
					const res = await request({
						url: '/score-service/score/list',
						method: 'GET'
					});
					
					if (res.success && res.data && res.data.productList) {
						// 转换商品数据格式
						this.products = res.data.productList.map(item => ({
							id: item.id,
							name: item.name,
							points: item.score,
							price: item.price,
							stock: item.stock,
							salesVolume: item.salesVolume,
							productInfo: item.productInfo,
							image: this.getProductImageUrl(item.productImage)
						}));
						
						console.log('获取积分商品列表成功:', this.products);
					} else {
						console.error('获取积分商品列表失败:', res.message);
						uni.showToast({
							title: res.message || '获取商品列表失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('获取积分商品列表异常:', error);
					uni.showToast({
						title: '获取商品列表失败',
						icon: 'none'
					});
				} finally {
					this.loading = false;
				}
			},
			
			// 获取商品图片完整URL
			getProductImageUrl(imageName) {
				if (!imageName) {
					return 'http://121.36.197.175:19000/test/default-product.png'; // 默认图片
				}
				
				// 如果已经是完整URL，直接返回
				if (imageName.startsWith('http')) {
					return imageName;
				}
				
				// 拼接完整的图片URL
				return `http://121.36.197.175:19000/test/${imageName}`;
			},
			
			// 下拉刷新
			async onRefresh() {
				this.refreshing = true;
				
				try {
					await this.initPageData();
				} catch (error) {
					console.error('刷新失败:', error);
				} finally {
					this.refreshing = false;
				}
			},
			
			// 分享商品
			shareProduct() {
				uni.showToast({
					title: '分享功能开发中',
					icon: 'none'
				});
			}
		}
	}
</script>

<style>
	.content {
		width: 100%;
		background-color: #f5f5f5;
		min-height: 100vh;
	}
	
	/* 自定义导航栏 */
	.nav-bar {
		background-color: #ffffff;
		border-bottom: 1rpx solid #f0f0f0;
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		z-index: 1000;
	}
	
	.status-bar {
		width: 100%;
		background-color: #ffffff;
	}
	
	.nav-content {
		display: flex;
		align-items: center;
		justify-content: space-between;
		height: 88rpx;
		padding: 0 30rpx;
		background-color: #ffffff;
	}
	
	.nav-left {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-shrink: 0;
	}
	
	.nav-title {
		font-size: 32rpx;
		font-weight: bold;
		color: #333;
		text-align: center;
		flex: 1;
	}
	
	.nav-right {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
		flex-shrink: 0;
	}
	
	.nav-icon {
		width: 40rpx;
		height: 40rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	/* 积分展示区 */
	.points-display {
		background-color: #4CAF50;
		padding: 40rpx 30rpx;
		color: #ffffff;
		text-align: center;
	}
	
	.points-label {
		font-size: 28rpx;
		margin-bottom: 10rpx;
	}
	
	.points-value {
		font-size: 60rpx;
		font-weight: bold;
	}
	
	/* 选项卡 */
	.tabs {
		display: flex;
		background-color: #ffffff;
		border-bottom: 2rpx solid #f0f0f0;
	}
	
	.tab-item {
		flex: 1;
		text-align: center;
		padding: 20rpx 0;
		font-size: 28rpx;
		color: #666;
		position: relative;
	}
	
	.tab-item.active {
		color: #4CAF50;
		font-weight: bold;
	}
	
	.tab-item.active::after {
		content: '';
		position: absolute;
		bottom: 0;
		left: 50%;
		transform: translateX(-50%);
		width: 40rpx;
		height: 4rpx;
		background-color: #4CAF50;
	}
	
	/* 商品列表 */
	.product-list {
		padding: 10rpx 8rpx;
		height: calc(100vh - 300rpx); /* 适应页面高度 */
	}
	
	.product-grid {
		display: flex;
		flex-wrap: wrap;
		justify-content: space-between;
	}
	
	.product-item {
		background-color: #ffffff;
		border-radius: 10rpx;
		overflow: hidden;
		margin-bottom: 12rpx;
		box-shadow: 0 2rpx 10rpx rgba(0,0,0,0.05);
		width: 49.2%; /* 增加宽度，减少间距到0.8% */
	}
	
	.product-image {
		width: 100%;
		height: 200rpx;
	}
	
	.product-info {
		padding: 15rpx;
	}
	
	.product-name {
		font-size: 26rpx;
		color: #333;
		margin-bottom: 8rpx;
		white-space: nowrap;
		overflow: hidden;
		text-overflow: ellipsis;
		font-weight: 500;
	}
	
	.product-stats {
		display: flex;
		justify-content: space-between;
		margin-bottom: 8rpx;
	}
	
	.stock, .sales {
		font-size: 20rpx;
		color: #666;
	}
	
	.product-points {
		font-size: 24rpx;
		color: #4CAF50;
		font-weight: bold;
		margin-bottom: 4rpx;
	}
	
	.product-price {
		font-size: 22rpx;
		color: #ff6b35;
		font-weight: 500;
	}
	
	/* 加载状态 */
	.loading-container {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 0;
	}
	
	.loading-text {
		margin-top: 20rpx;
		font-size: 28rpx;
		color: #666;
	}
	
	/* 空状态 */
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 100rpx 0;
	}
	
	.empty-image {
		width: 200rpx;
		height: 200rpx;
		margin-bottom: 30rpx;
	}
	
	.empty-text {
		font-size: 28rpx;
		color: #999;
	}
	
	.empty-content {
		padding: 100rpx 0;
		text-align: center;
		color: #999;
		font-size: 28rpx;
	}
</style>
